<template>
    <el-dialog :title="titleMap[mode]" v-model="visible" :width="600" destroy-on-close @closed="$emit('closed')">
        <el-form :model="form" :rules="rules" ref="dialogForm" :disabled="mode==='show'" label-width="80px" label-position="left">
            <el-form-item label="父路径" prop="parentId">
                <sc-table-select v-model="defaultValue" :apiObj="apiObj" row-key="id" :table-width="600" :disabled="mode!=='add'" :props="dictProps" @change="changeSelect">
                    <template #header="{form, submit}">
                        <el-form :inline="true" :model="form">
                            <el-form-item>
                                <el-input v-model="form.dictCode" placeholder="字典编码" clearable :teleported="false"/>
                            </el-form-item>
                            <el-form-item>
                                <el-input v-model="form.dictName" placeholder="字典名称" clearable :teleported="false"/>
                            </el-form-item>
                            <el-form-item>
                                <el-button type="primary" @click="submit">查询</el-button>
                            </el-form-item>
                        </el-form>
                    </template>
                    <el-table-column prop="dictName" label="字典名称" min-width="150"></el-table-column>
                    <el-table-column prop="dictCode" label="字典编码" width="200"></el-table-column>
                </sc-table-select>
            </el-form-item>
            <el-form-item label="编码" prop="dictCode">
                <el-input v-model="form.dictCode" clearable :disabled="mode==='edit'" placeholder="字典编码">
                    <template #prepend v-if="mode==='add' && _prefix">
                        <div v-text="_prefix"></div>
                    </template>
                </el-input>
            </el-form-item>
            <el-form-item label="字典名称" prop="dictName">
                <el-input v-model="form.dictName" clearable placeholder="字典显示名称"></el-input>
            </el-form-item>
            <el-form-item label="状态" prop="status">
                <sc-select v-model="form.status" dict="ENABLE_STATUS" filterable style="width: 100%;"></sc-select>
            </el-form-item>
            <el-form-item label="备注" prop="dictNote">
                <el-input v-model="form.dictNote" type="textarea" maxlength="255" show-word-limit/>
            </el-form-item>
        </el-form>
        <template #footer>
            <el-button @click="visible=false">取 消</el-button>
            <el-button type="primary" v-if="mode!=='show'" :loading="isSaveing" @click="submit()">保 存</el-button>
        </template>
    </el-dialog>
</template>

<script>
export default {
    emits: ['success', 'closed'],
    data() {
        const checkExist = (rule, value, callback) => {
            if (!value || value === '') {
                callback() //条件不满足 也需要回调、返回，此次回调成功，因为外面有其他规则校验
                return;
            }
            this.exists(rule.field, value).then(res => {
                if (res.code !== 200) {
                    callback(new Error(res.msg))
                } else if (res.data) {
                    callback(new Error('字典已存在')) // 返回校验失败
                } else {
                    callback()
                }
            })
        };
        return {
            mode: "add",
            titleMap: {
                add: '新增字典',
                edit: '编辑字典'
            },
            apiObj: this.$API.system.dict,
            visible: false,
            isSaveing: false,
            form: {
                id: "",
                dictName: "",
                dictCode: "",
                status: "ENABLED",
                parentId: ""
            },
            rules: {
                dictCode: [
                    {required: true, message: '请输入编码'}, {validator: checkExist, trigger: 'blur'}
                ],
                dictName: [
                    {required: true, message: '请输入字典名称'}
                ]
            },
            defaultValue: {id: "0", dictName: "顶级字典"},
            dictProps: {
                value: "id",
                label: "dictName",
            }
        }
    },
    mounted() {

    },
    computed: {
        _prefix() {
            return this.defaultValue.parentCode ? this.defaultValue.parentCode + '_' : ''
        }
    },
    methods: {
        //显示
        open(mode = 'add') {
            this.mode = mode;
            this.visible = true;
            return this;
        },
        //表单提交方法
        submit() {
            this.$refs.dialogForm.validate(async (valid) => {
                if (valid) {
                    this.isSaveing = true;
                    let res;
                    if (this.mode === 'add') {
                        const data = {};
                        Object.assign(data, this.form)
                        data.dictCode = this._prefix + this.form.dictCode
                        res = await this.$API.system.dict.post(data);
                    } else {
                        res = await this.$API.system.dict.put(this.form);
                    }
                    this.isSaveing = false;
                    if (res.code === 200) {
                        this.$emit('success', this.form, this.mode)
                        this.visible = false;
                        this.$message.success("操作成功")
                    } else {
                        await this.$alert(res.msg, "提示", {type: 'error'})
                    }
                }
            })
        },
        // 验证字段是否存在
        async exists(name, value) {
            const fieldValue = this.mode === 'add' ? this._prefix + value : value;
            return await this.$API.system.dict.exists(name, fieldValue, this.form.id);
        },
        //表单注入数据
        setData(data) {
            //可以和上面一样单个注入，也可以像下面一样直接合并进去
            Object.assign(this.form, data)
        },
        setDefaultValue(data) {
            this.defaultValue = data
            return this;
        },
        changeSelect(data) {
            this.form.parentId = data.id
            this.defaultValue.id = data.id
            this.defaultValue.dictName = data.dictName
            this.defaultValue.parentCode = data.dictCode
        }
    }
}
</script>

<style>
</style>
